/*
 * @Date: 2025-01-19 11:51:00
 * @LastEditors: zl 1077167261@qq.com
 * @LastEditTime: 2025-01-19 17:40:13
 * @FilePath: \vue-admin\src\utils\request.js
 */
import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
const service = axios.create({
  baseURL: "https://api-hmzs.itheima.net/tj",
  timeout: 5000, // request timeout
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 每次请求添加token
    const token = store.state.user.token;
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response.status === 401) {
      // 1. 跳转到登录
      router.push("/login");
      // 2. 清空用户数据
      store.commit("user/clearUserInfo");
    }
    Message.error(error.response.data.msg);
    return Promise.reject(error);
  }
);

export default service;
